<div>
    <span>malu</span>
    <ul>
        <li>码路</li>
        <li>漫漫</li>
    </ul>
    码路教育
</div>

<script>
    function dom2tree(dom) {
        const obj = {}
        obj.tag = dom.tagName?.toLowerCase();
        obj.children = []
        Array.from(dom.childNodes).forEach(child => {
            if (child.nodeType === 3) {
                if (!child.textContent.trim()) return;
                obj.textContent = child.textContent.trim();
                return
            }
            obj.children.push(dom2tree(child))
        })
        if (!obj.children.length) delete obj.children;
        return obj
    }
    let div = document.getElementsByTagName("div")[0]

    let res = dom2tree(div)
    console.log(JSON.stringify(res));

    // let res = {
    //     tag: 'div',
    //     children: [
    //         { tag: 'span', children: [] },
    //         {
    //             tag: 'ul',
    //             children: [
    //                 { tag: 'li', children: [] },
    //                 { tag: 'li', children: [] }
    //             ]
    //         }
    //     ]
    // };
</script>